<?php

namespace ms\controllers;

use Yii;
use common\models\SysAdminUser;
use common\models\searchs\SearchSysAdminUser;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\models\BaseAdminSite;
use common\models\BaseSite;
use common\models\SysUserSupplier;
use common\models\SysSupplier;
use common\models\BaseAdminDes;
use common\models\AfterSalesDest;
use common\models\BaseBrand;

/**
 * SysAdminUserController implements the CRUD actions for SysAdminUser model.
 */
class SysAdminUserController extends \ms\components\Controller2015
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all SysAdminUser models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new SearchSysAdminUser();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    
    /**
     * Lists all SysAdminUser models.
     * @return mixed
     */
    public function actionAdminSite()
    {
    	$searchModel = new SearchSysAdminUser();
    	$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    
    	return $this->render('admin-user-site', [
    		'searchModel' => $searchModel,
    		'dataProvider' => $dataProvider,
    	]);
    }

    /**
     * Displays a single SysAdminUser model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new SysAdminUser model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new SysAdminUser();
        if ($model->load(Yii::$app->request->post())) {
        	$model->password = md5($model->password);
        	if (f_s('site_id')!=0) {
        	   $model->site_id = 1;
        	}
        	if($model->save()){
        		return $this->redirect(['view', 'id' => $model->id]);
        	}
        }
            return $this->render('create', [
                'model' => $model,
            ]);
    }

    /**
     * Updates an existing SysAdminUser model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
		$old_pwd = $model->password;
        if ($model->load(Yii::$app->request->post())) {
        	$new_pwd = $model->password;
        	if($old_pwd != $new_pwd){
        		$model->password = md5($new_pwd);
        	}
        	$model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing SysAdminUser model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }
    
    
    /**
     * 
     * @Title: actionAdminUserSite
     * @Description: 
     * @return: Ambigous <string, string>
     * @author: yulong.wang
     * @date: 2015-1-15下午7:41:36
     */
    public function actionAdminUserSite()
    {
    	$admin_user_id = f_get('admin_user_id', 0);
        $model = new BaseAdminSite();
        $site_arr = f_s('site_array_list');
        $admin_user_site_arr = BaseAdminSite::find()->indexBy('site_id')->where(['admin_user_id' => $admin_user_id])->asArray()->all();
        $sites = [];
        if ($admin_user_site_arr) {
            $admin_user_site = array_keys($admin_user_site_arr);
            if ($site_arr) {
                foreach ($site_arr as $key=>$value) {
                	$sites[$key]['id'] = $key;
                	$sites[$key]['name'] = $value;
                    $sites[$key]['checked'] = in_array($key,$admin_user_site) ? 1 : 0;
                }    
            }
        } else {
            foreach ($site_arr as $key=>$value) {
                $sites[$key]['id'] = $key;
                $sites[$key]['name'] = $value;
                $sites[$key]['checked'] = 0;
            }
        }
        
        if (isset($_POST['save'])) {
            if (isset($_POST['site_id'])) {
                $connection = Yii::$app->db;//事务开始
                $transaction = $connection->beginTransaction();
                try {
                    $rows = BaseAdminSite::findOne(['admin_user_id'=>$admin_user_id]); 
                    if ($rows) {
                        $delete = BaseAdminSite::deleteAll(['admin_user_id'=>$admin_user_id]);
                        if ($delete) {
                            foreach ($_POST['site_id'] as $v) {
                                $model = new BaseAdminSite();
                                $model->admin_user_id = $admin_user_id;
                                $model->site_id = $v;
                                $model->save();
                            }
                        } 
                    } else {
                        foreach ($_POST['site_id'] as $v) {
                            $model = new BaseAdminSite();
                            $model->admin_user_id = $admin_user_id;
                            $model->site_id = $v;
                            $model->save();
                        }
                    }
                    $transaction->commit();   	//事务结束
                } catch (\Exception $e) {
           		   $transaction->rollBack();
           		}
           		return $this->render('view', ['model' => $this->findModel($admin_user_id)]);
            } else {
                $rows = BaseAdminSite::findOne(['admin_user_id'=>$admin_user_id]); 
                if ($rows) {
                    $delete = BaseAdminSite::deleteAll(['admin_user_id'=>$admin_user_id]);
                    return $this->render('view', ['model' => $this->findModel($admin_user_id)]);
                } else {
                    return $this->render('admin_user_site', ['model' => $model,'sites' => $sites]);
                }
            }
        } else {
            return $this->render('admin_user_site', ['model' => $model,'sites' => $sites]);
        } 
    }

    
    /**
     * @Title: actionAssignSite
     * @Description: 地市分配
     * @return: return_type
     * @author: weilong.yin
     * @date: 2015-4-10 下午1:04:54
     *
     * @update: ShengHui
     * @date: 2015-07-13
     */
    public function actionAssignSite(){
    	$des_all = AfterSalesDest::getAllDesOrderByProvince();

    	if(isset($_GET['admin_user_id'])&&!empty($_GET['admin_user_id'])){
    		return $this->render('admin-user-des',['des_all'=>$des_all]);
    	}else if(isset($_POST['save'])){

			if(isset($_POST['des_id'])){
				$connection = Yii::$app->db;//事务开始
				$transaction = $connection->beginTransaction();
				try {
					$rows = BaseAdminDes::find()->where(['admin_user_id'=>$_POST['admin_user_id']])->asArray()->all();
					if($rows){
						$delete = BaseAdminDes::deleteAll(['admin_user_id'=>$_POST['admin_user_id']]);
						if ($delete) {
							foreach ($_POST['des_id'] as $v) {
								$model = new BaseAdminDes();
								$model->admin_user_id = $_POST['admin_user_id'];
								$model->des_id = $v;
								$model->save();
							}
						}
					}else{
						foreach ($_POST['des_id'] as $v) {
							$model = new BaseAdminDes();
							$model->admin_user_id = $_POST['admin_user_id'];
							$model->des_id = $v;
							$model->save();
						}
					}
					
					$transaction->commit();   	//事务结束
				}catch (\Exception $e){
					$transaction->rollBack();
				}
				return $this->render('view', ['model' => $this->findModel($_POST['admin_user_id'])]);
			}else{
				$rows = BaseAdminDes::find()->where(['admin_user_id'=>$_POST['admin_user_id']])->asArray()->all();
				if ($rows) {
					$delete = BaseAdminDes::deleteAll(['admin_user_id'=>$_POST['admin_user_id']]);
					return $this->render('view', ['model' => $this->findModel($_POST['admin_user_id'])]);
				} else {
					return $this->render('view', ['model' => $this->findModel($_POST['admin_user_id'])]);
				}
				
			}
    	}
    	
    }
    /**
     * Finds the SysAdminUser model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return SysAdminUser the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = SysAdminUser::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    /**
     *
     * @Title: actionResetAdminUserPassword
     * @Description: 重置密码
     * 根据ajax传递过来的admin_user_id和随机生成的6位数密码，修改管理员表记录
     * @return: json
     * @author: yulong.wang
     * @date: 2014-12-25 下午5:36:59
     */
    public function actionResetAdminUserPassword($pwd,$admin_user_id,$email){
    	$pwds = md5($pwd);
    	$admin_user = SysAdminUser::updateAll(['password'=>$pwds],['id'=>$admin_user_id]);
    	if($admin_user){
    		$return['status'] = 1;
    		$return['message'] = '重置密码成功';
    		$msg = '我要订货网提示您,你重置后的新密码:'.$pwd.';为了您的账户安全,请尽快修改新密码【我要订货网】';
    		  \Yii::$app->mailer->compose()->setFrom(EMAIL)->setTo($email)->setTextBody($msg)->setSubject('密码重置')->send();
    	}else{
    		$return['status'] = 0;
    		$return['message'] = '重置密码失败';
    	}
    	return json_encode($return);
    }
    
    /**
     * @Title: actionResetpassword
     * @Description: 管理员修改自己的密码
     * @return: Ambigous <string, string>
     * @author: KOUPING.SUN
     * @date: 2015-1-9 下午3:58:44
     */
    public function actionResetpassword(){
    	$id = f_s('admin_user')['id'];
    	if($id == 0){
            echo '获取信息失败，请重新登录系统';
    	}
    	if(isset($_POST['sub'])){
            //f_d($_POST);
            $user_info = SysAdminUser::findOne($id);
            $old_old_pwd = $user_info->password;
            $old_pwd = md5($_POST['old_pwd']);
            $new_pwd = md5($_POST['new_pwd']);
            //f_d($new_pwd);
            if($old_pwd == $old_old_pwd){
                //修改数据库
                $user_info->password = $new_pwd;
                $out = $user_info->save();
                //f_d($out);
                if($out){
                    //f_d($out);
                    return $this->render('resetpassword',[
                                    'message'=>'修改成功',
                    ]);
                }else{
                    return $this->render('resetpassword',[
                                    'message'=>'修改失败',
                    ]);
                }
            }else{
                return $this->render('resetpassword',[
                                'message'=>'原密码错误',
                ]);
            }
    	} else {
            return $this->render('resetpassword',[
                'message'=>'修改密码，慎重使用',
            ]);
    	}
    	
    }
    
    /**
     * @Title: actionAddsupplier
     * @Description: 管理员添加上游厂商
     * @return: view
     * @author: weijuan.huang
     * @date: 2015-3-10 10:05:02
     */
    public function actionAddsupplier()
    {
        $msg = '';
        $supplier = SysSupplier::find()->asArray()->all();
        
        if(!empty($_POST['uid']) && !empty($_POST['sid']) ){
            $id = $_POST['uid'];
            $sid = $_POST['sid'];
            $isset = SysUserSupplier::find()->where(['uid'=>$id,'sid'=>$sid])->asArray()->all();
            if(empty($isset)){
                $model = new SysUserSupplier;
                $model->uid = $id;
                $model->sid = $sid;
                $model->save();
            }else{
                $msg = '注意, 该上游厂商已存在！';
            }
            
        }else{
            $id = f_get('id');
        }
        $adminname = SysAdminUser::findone($id)->attributes;
        $user_supplier = SysUserSupplier::find()->where(['uid'=>$id])->asArray()->all();
        return $this->render('addsupplier',[
                'user_id'=>$id,
                'adminname'=>$adminname,
                'supplier'=>$supplier,
                'user_supplier'=>$user_supplier,
                'msg'=>$msg,
        ]);
        
    }
    
    /**
     * @Title: actionDeletesupplier
     * @Description: 管理员删除上游厂商
     * @return: view
     * @author: weijuan.huang
     * @date: 2015-3-10 11:03:02
     */
    public function actionDeletesupplier($sid,$uid)
    {
        $msg = '';
        $delete = SysUserSupplier::deleteAll(['sid'=>$sid,'uid'=>$uid]);
        if($delete){
            $msg = '该上游厂商已删除！';
        }else{
            $msg = '注意, 上游厂商删除失败！';
        }
        
        $user_supplier = SysUserSupplier::find()->where(['uid'=>$uid])->asArray()->all();
        $supplier = SysSupplier::find()->asArray()->all();
        $adminname = SysAdminUser::findone($uid)->attributes;
        return $this->render('addsupplier',[
                'user_id'=>$uid,
                'adminname'=>$adminname,
                'supplier'=>$supplier,
                'user_supplier'=>$user_supplier,
                'msg'=>$msg,
        ]);
        
    }
    /**
     * @Title: actionAddsite
     * @Description: 批量为某类添加 新开的站点权限
     * @return: return_type
     * @author: admin
     * @date: 2015年5月14日 下午3:13:25
     */
    public function actionAddsite(){
    	header("Content-Type: text/html; charset=UTF-8");
    	if(isset($_POST['add'])){
    		$site_id = $_POST['site_id'];
    		$admin_ids = $_POST['admin_id'];
    		$tianjia_shuliang = 0;
    		foreach ($admin_ids as $value){
    			$had = BaseAdminSite::find()->where(['admin_user_id'=>$value,'site_id'=>$site_id])->asArray()->one();
//     			f_d($had);
    			if(!$had){
    				$model = new BaseAdminSite();
    				$model->admin_user_id = $value;
    				$model->site_id = $site_id;
    				$redult = $model->save();
    				if($redult){
                                    $tianjia_shuliang = $tianjia_shuliang + 1;
    				}
//     				f_d($model->errors);
    			}
    		}
    		
    		return $this->msg('成功修改'.$tianjia_shuliang.'条数据', 'index');
    	}else{
    		$sites = BaseSite::getAllSite(1);
    		$admin_users = SysAdminUser::find()->orderBy('CONVERT(user_name USING gbk ) COLLATE gbk_chinese_ci ASC')->asArray()->all();
    		return $this->render('addsite',[
    			'sites'=>$sites,
    			'admin_user'=>$admin_users,
    		]);	
    	}
    }
    
    /**
     * @description:角色下管理员
     * @return: return_type
     * @author: jiangtao.ren
     * @date: 2015年8月7日下午2:44:39
     * @review_user:weijuan.huang
    */
    public function actionAdminUserAjax(){
    	$data = '';
    	$item = f_get('item');
    	$sql = "SELECT user_id FROM `dh_sys_auth_assignment` WHERE item_name = '$item'";
    	$userIds = SysAdminUser::findBySql($sql)->asArray()->all();
    	foreach ($userIds as $key =>$value){
    		$user_id[] = $value['user_id']; 
    	}
    	$admin_users = SysAdminUser::find()->where(['in','id',$user_id])->orderBy('CONVERT(user_name USING gbk ) COLLATE gbk_chinese_ci ASC')->asArray()->all();
    	foreach ($admin_users as $k=>$vo){
    		$id = $vo['id'];
    		$name = $vo['user_name'];
    		$data .= "<label class='checkbox' style='width:250px;float:left;' ><input type='checkbox' name='admin_id[]' value='$id'>$name</label>";
    	}
    	echo json_encode($data);
    }
}
